#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Script to generate a reduced image thanks to the right-click 'Open with' menu. (You need to set this manually).
#
# @author Jean-Baptiste Fiot <hellwoxx@gmail.com>
# @version Jan 2011

import os, wx, traceback, sys, subprocess

  

class MyFrame(wx.Frame):
  def __init__(self, zoom):
    
    
    
    #################################################
    #                   GUI stuff                   #
    #################################################
    
    self.zoom = zoom
    self.model = 1
    wx.Frame.__init__(self, None, -1, "[Fiot 2011] Resize")
    self.panel = wx.Panel(self, -1)
    
    # Ratio
    self.ratio = wx.Slider(self.panel, id=-1, size = wx.Size(300, -1), minValue=1, maxValue=99, value=50, style=wx.TE_MULTILINE)
    
    # Button	
    launch_img = wx.Image(os.path.join(os.path.dirname(sys.argv[0]),"GUI_pics","apply.png"), wx.BITMAP_TYPE_ANY).ConvertToBitmap()
    self.launchButton = wx.BitmapButton(self.panel, id=-1, bitmap=launch_img)
    self.launchButton.Bind(wx.EVT_BUTTON, self.OnLaunch)
    
    # Sizer
    self.sizer = wx.FlexGridSizer(cols = 2)
    self.sizer.Add(self.ratio,1,wx.EXPAND|wx.LEFT|wx.RIGHT,10)
    self.sizer.Add(self.launchButton, flag = wx.ALIGN_CENTER)

    self.status = wx.StatusBar(self.panel, id = -1, name = "statusBar")
    self.status.SetStatusText("Please select the desired ratio and press the OK button.")

    self.vertsizer = wx.FlexGridSizer(cols = 1)
    self.vertsizer.Add(self.sizer)
    self.vertsizer.Add(self.status)
    
    border = wx.BoxSizer()
    border.Add(self.vertsizer, 0, wx.ALL, 10)
    
    self.panel.SetSizerAndFit(border)
    self.Fit()
  

    
  #################################################
  #                   Events                      #
  #################################################
  
  def OnLaunch(self, evt):
    if len(sys.argv) >=2 :
      input_file = sys.argv[1]      
      output_file = os.path.splitext(input_file)[0] + '_' + str(self.ratio.GetValue()) + '%' + os.path.splitext(input_file)[1]
      
      if not os.path.exists(output_file):
        to_run = ['convert', '-resize', str(self.ratio.GetValue()) + '%', input_file, output_file] 
        self.status.SetStatusText(' '.join(to_run))
        subprocess.call(to_run)
        self.status.SetStatusText('Done.')
    else:
      self.status.SetStatusText('Nothing to run.')
      


class MyApp(wx.App):
    def OnInit(self):
        self.MyFrame = MyFrame(2)
        self.MyFrame.Center(wx.BOTH)
        self.MyFrame.Show()
        return True


app = MyApp(False)

# Traceback
def Myexcepthook(type, value, tb):
        lines=traceback.format_exception(type, value, tb)
        wx.MessageBox("\n".join(lines), "Traceback Error")
sys.excepthook=Myexcepthook


app.MainLoop()

